package com.admin.system.config;

import com.admin.system.security.jwt.SecurityUtils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author caixiaofeng
 * @version 1.0
 * @Description: <<>>
 * @company cxf
 * @create 2021-01-31 21:45
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入时填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        //实体类中有该属性时调用
        if (metaObject.hasSetter("createTime")) {
            this.fillStrategy(metaObject, "createTime", LocalDateTime.now());
        }
        if (metaObject.hasSetter("createdBy")) {
            this.fillStrategy(metaObject, "createdBy", SecurityUtils.getCurrentUserId());
        }
    }

    /**
     * 更新时填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        //更新对象时未设置值时填充
        // if (this.getFieldValByName("updateTime", metaObject) == null) { }
        // if (this.getFieldValByName("updatedBy", metaObject) == null) { }
        if(metaObject.hasSetter("updateTime")){
            this.fillStrategy(metaObject, "updateTime", LocalDateTime.now());
        }
        if(metaObject.hasSetter("updatedBy")){
            this.fillStrategy(metaObject, "updatedBy", SecurityUtils.getCurrentUserId());
        }
    }
}
